﻿using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SubFps
{
    static class Installer
    {
        public static void Setup()
        {
            try
            {
                var classes = Registry.ClassesRoot;
                var path = CheckFile();
                var srtfile = CreateRegistry(classes, "srtfile", "Movie Subtitle File");
                var shell = CreateRegistry(srtfile, "shell", null);
                var srtFixer = CreateRegistry(shell, "srtFixer", "Edit in SrtFixer");
                CreateRegistry(srtFixer, "Command", string.Format("\"{0}\" \"%1\"", path));
                CreateRegistry(classes, ".srt", "srtfile");
            }
            catch { }
        }

        private static string CheckFile()
        {
            var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            var directoryPath = Path.Combine(programFiles, "SrtFixer");
            var filePath = Path.Combine(directoryPath, "SrtFixer.exe");
                var exePath = Application.ExecutablePath; 
            if (FileShouldBeCopied(filePath, exePath))
            {
                Directory.CreateDirectory(directoryPath);
                File.Copy(exePath, filePath, true);
                Helper.ShowInfo("File has been copeid to " + filePath);
            }
            return filePath;
        }

        private static bool FileShouldBeCopied(string dest, string src)
        {
            if (!File.Exists(dest))
                return true;
            if (dest.Equals(src, StringComparison.InvariantCultureIgnoreCase))
                return false;
            return new FileInfo(dest).LastWriteTime < new FileInfo(src).LastWriteTime;
        }

        private static RegistryKey CreateRegistry(RegistryKey parentKey, string subKeyName, string defaultValue)
        {
            var key = parentKey.OpenSubKey(subKeyName);
            if (key == null)
            {
                key = parentKey.CreateSubKey(subKeyName);
            }
            if (defaultValue != null)
            {
                var defaultVal = key.GetValue("") as string;
                if (defaultVal == null)
                {
                    key.SetValue("", defaultValue);
                }
            }
            return key;
        }
    }
}
